package validates

import (
	"bytes"
	"fmt"
	"myapp/dal/model"
	"myapp/dal/query"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/html"
)

type Need struct {
	ID          int              `json:"id"`
	Title       string           `json:"title" binding:"required" label:"标题"`   // 必填字段
	Type        int              `json:"type" binding:"lte=1" label:"类型"`       // 数量必须小于等于 1
	Content     string           `json:"content" binding:"required" label:"内容"` // 必填字段
	Company     string           `json:"company" binding:"required" label:"公司"`
	Time        string           `json:"time"`
	Images      []string         `json:"images"`
	TypeName    string           `json:"type_name" label:"类型"`
	CategoryIds string           `json:"category_ids" label:"合作类型"` // 合作类型
	Categories  []model.Category `json:"categories" label:"分类"`

	TitleEn    string `json:"title_en" label:"title"`      // 必填字段
	ContentEn  string `json:"content_en"  label:"content"` // 必填字段
	CompanyEn  string `json:"company_en"  label:"company"`
	TypeNameEn string `json:"type_name_en" label:"type"`
	TimeEn     string `json:"time_en"`
	Status     int32  `json:"status"` // 审核状态:2=审核失败,0=未审,1=已审核
	IsTop      int32  `json:"is_top"` // 是否置顶
}

const (
	TypeGong = 0
	TypeQiu  = 1
)

var TypeEnumMap = map[int]string{
	TypeGong: "供应",
	TypeQiu:  "需求",
}

var TypeEnEnumMap = map[int]string{
	TypeGong: "Supply",
	TypeQiu:  "Demand",
}

// 处理函数：将 `Need` 转换为 `CustomNeed`，并添加额外字段
func ProcessNeed(nd *model.Need) Need {
	// 获取枚举的中文描述
	typeName := "未知类型" // 默认值
	typeNameEn := "No"
	if name, exists := TypeEnumMap[int(nd.Type)]; exists {
		typeName = name
	}
	if nameEn, exists := TypeEnEnumMap[int(nd.Type)]; exists {
		typeNameEn = nameEn
	}

	// 假设查询分类信息的函数是这样
	var CategoryIds []int
	if len(nd.CategoryIds) > 0 {
		categoryIds := strings.Split(nd.CategoryIds, ",")
		for _, v := range categoryIds {
			vid, _ := strconv.Atoi(v)
			CategoryIds = append(CategoryIds, vid)
		}
	}
	var categories []model.Category
	if len(nd.CategoryIds) > 0 {
		categories, _ = GetCategoryByIDs(CategoryIds) // 简化的错误处理
	}

	images := strings.Split(nd.Images, ",")

	// 返回自定义结构体
	time, _ := FormatTime(nd.CreatedAt.Format("2006-01-02 15:04:05"), false)
	timeEn, _ := FormatTime(nd.CreatedAt.Format("2006-01-02 15:04:05"), true)
	return Need{
		ID:         int(nd.ID),
		Type:       int(nd.Type),
		Title:      nd.Title,
		Content:    removeHTMLTags(nd.Content),
		Company:    nd.Company,
		TypeName:   typeName,
		Time:       time,
		Categories: categories,
		TitleEn:    nd.TitleEn,
		ContentEn:  nd.ContentEn,
		CompanyEn:  nd.CompanyEn,
		TypeNameEn: typeNameEn,
		TimeEn:     timeEn,
		Images:     images,
		Status:     nd.Status,
		IsTop:      nd.IsTop,
	}
}

func removeHTMLTags(input string) string {
	// 解析HTML
	doc, err := html.Parse(strings.NewReader(input))
	if err != nil {
		return ""
	}

	// 遍历HTML节点并提取文本内容
	var buffer bytes.Buffer
	var traverse func(*html.Node)
	traverse = func(n *html.Node) {
		// 只处理文本节点
		if n.Type == html.TextNode {
			buffer.WriteString(n.Data)
		}

		// 递归遍历子节点
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			traverse(c)
		}
	}

	// 开始遍历文档节点
	traverse(doc)

	// 返回去除标签后的文本
	return buffer.String()
}

// 格式化时间为：刚刚、几分钟前、几小时前、超过24小时显示具体日期
func FormatTime(inputTime string, en bool) (string, error) {
	// 解析输入的时间字符串
	layout := "2006-01-02 15:04:05"
	t, err := time.Parse(layout, inputTime)
	if err != nil {
		return "", err
	}

	// 获取当前时间
	now := time.Now()

	// 计算时间差
	diff := now.Sub(t)

	var msgMap = map[string]map[string]string{
		"zh": {
			"sec":  "刚刚",
			"min":  "分钟前",
			"hour": "小时前",
		},
		"en": {
			"sec":  "just",
			"min":  "minutes ago",
			"hour": "hours ago",
		},
	}

	lang := "zh"
	if en {
		lang = "en"
	}
	// 判断时间差并返回相应的格式
	if diff < time.Minute {
		return msgMap[lang]["sec"], nil
	} else if diff < time.Hour {
		// 小于一小时，显示几分钟前
		minutes := int(diff.Minutes())
		return fmt.Sprintf("%d "+msgMap[lang]["min"], minutes), nil
	} else if diff < 24*time.Hour {
		// 小于24小时，显示几小时前
		hours := int(diff.Hours())
		return fmt.Sprintf("%d "+msgMap[lang]["hour"], hours), nil
	} else {
		// 超过24小时，显示具体日期
		return t.Format("2006-01-02"), nil
	}
}

// 获取分类信息的示例函数
func GetCategoryByIDs(categoryIDs []int) ([]model.Category, error) {
	// 查询并返回分类数据
	// 假设返回一个简单的分类列表
	var categories []model.Category
	// 模拟返回
	for _, id := range categoryIDs {
		category, err := query.Category.Where(query.Category.ID.Eq(int32(id))).Take()
		if err == nil && category != nil {
			categories = append(categories, *category)
		}
	}
	return categories, nil
}
